package com.cz.util;

import java.io.File;  
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.cz.test.Sample2;

import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;  


public class TextUtil {

	private static Logger logger = Logger.getLogger(TextUtil.class);
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		String str = textReader(null);
//		String str = "氦闪并没有发生，";
		List list = textCut(str);
		Iterator<String> it = list.iterator();
		while(it.hasNext()) {
			String s = it.next().toString();
			logger.info(s.length());
		}
		logger.info(str.length());
	}
	
	public static String textReader(String path) throws IOException {
		 /* 读入TXT文件 */
		StringBuilder sb = new StringBuilder();
        String pathname = "input/" + path +".txt"; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径  
        File filename = new File(pathname); // 要读取以上路径的input。txt文件  
        InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // 建立一个输入流对象reader  
        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言  
        String line = "";  
        line = br.readLine();  
        sb.append(line);
        while (line != null) {  
            line = br.readLine(); // 一次读入一行数据  
            sb.append(line);
        }  
        return sb.toString();
	}
	
	public static String textReaderWithCode(String path, String code) throws IOException {
		String pathname = "input/" + path +".txt"; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径  
		File file = new File(pathname);
		InputStream input = new FileInputStream(file);  
		StringBuffer buffer = new StringBuffer();  
		byte[] bytes = new byte[1024];  
		for(int n ; (n = input.read(bytes))!=-1 ; ){  
			buffer.append(new String(bytes,0,n,code));
		}
		input.close();
//		String s = buffer.toString().replaceAll("\n", "").replaceAll(" ", "");
		return buffer.toString();
	}
	
	
	public static String textReaderWithCodeNew(String path, String code) throws IOException {
		String pathname = "input/" + path +".txt"; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径
		File file = new File(pathname);
		return FileUtils.readFileToString(file,"UTF-8" );
	}
	
	public static void reNameFile(String path) {
		String pathname = "input/" + path +".txt"; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径  
		File file = new File(pathname);
		if(file.exists()) {
			File newFile = new File("input/" + path +"_done.txt");  
			file.renameTo(newFile);
		}else {
			logger.error("完成后，文件更名错误：文件不存在！");
		}
	}
	
	public static String textPreHandle(String text) {
		text = text.replaceAll("\r\n", "");//删除换行
		text = text.replaceAll("（", "(");
		text = text.replaceAll("）", ")");
		text = text.replaceAll("(?<=\\()[^\\)]+", "");//删除小括号内容
		text = text.replaceFirst(" ", "[p1000]");
		text = text.replaceAll(" ", "");//删除空格
		text = text.replaceAll("　", "");//删除空格……
		text = text.replaceAll("……", "。");
		text = text.replaceAll("mm", "毫米");
		text = text.replaceAll("kg", "千克");
		text = text + "。";
		return text;
	}
	
	
	public static void textWriter(String name, String fileContent) throws IOException {
		/* 写入Txt文件 */  
        File writename = new File("output/" + name); // 相对路径，如果没有则要建立一个新的output.txt文件  
        writename.createNewFile(); // 创建新文件  
        BufferedWriter out = new BufferedWriter(new FileWriter(writename));  
        out.write(fileContent); // \r\n即为换行  
        out.flush(); // 把缓存区内容压入文件  
        out.close(); // 最后记得关闭文件
	}
	
	public static void textWriterNew(String name, String fileContent) throws IOException {
		/* 写入Txt文件 */
        File writename = new File("output/" + name); // 相对路径，如果没有则要建立一个新的output.txt文件  
        FileUtils.writeStringToFile(writename,fileContent, "UTF-8", false);
	}
	
	public static List<String> textCut(String str) throws Exception{
		final int maxLength = 470;
		List<String> list = new ArrayList<String>(0);
		int textlength = str.length();
		String[] strArray = null;
		if(textlength > 300) {
			strArray = str.split("。|；|：|？|！|;|\\?|!");
		}else {
			strArray =  new String[]{str};
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < strArray.length; i++) {
			if((sb.length() + strArray[i].length() < maxLength) && strArray[i] != null && !strArray[i].equals("null")) {
				sb.append(strArray[i]+"。");
				logger.debug("i:" + i + ",  sb:" + sb);
				logger.debug("strArray.length:" + strArray.length + ", i:" + i);
				logger.debug("strArray[i]:" + strArray[i]);
				if(i == strArray.length - 1){
					logger.debug("最后一段：" + strArray[i]);
					if(strArray[i] != null) {
						list.add(sb.toString());
					}
				}
			}else {
				if(sb.length()>maxLength) {
					logger.error("溢出文本长度:" + sb.length());
					logger.error("溢出文本:" + sb);
					throw new Exception("切割后的文本长度超过" + maxLength + "个字符.");
				}
				list.add(sb.toString());
				sb = new StringBuffer();
				sb.append(strArray[i]+"。");
			}
			logger.debug("i:" + i + ",  sb:" + sb);
		}
		return list;
	}
	
	/**
	 * 应用主题模板
	 * @param title
	 * @param speecher
	 * @param text
	 * @return
	 */
	public static String modelApply(String title, String speecher, String text) {
		text = title + "[p1000]播讲者：美音天团[p2000]\n" + text + "\n[p2000]本章节播讲完毕，感谢您的收听。[p3000]";
		return text;
	}
	
	/**
	 * 获取文本开头
	 * @param title
	 * @param speecher
	 * @return
	 */
	public static String getStartText(String title, String speecher, int type) {
		String text = title + "[p1000]播讲者：美音天团[p2000]\n";
		if(type == 0) {
			text = "[p1000]播讲者：美音天团[p2000]\n";
		}else if(type == 1) {
			text = "[p1000]播讲者：美音天团[p2000]\n";
		}else if(type == 2) {
			text = " ";
		}
		return text;
	}
	
	/**
	 * 获取文本结尾
	 * @param title
	 * @param speecher
	 * @return
	 */
	public static String getEndText(String title, String speecher, int type) {
		String text = "\n[p2000]本章节播讲完毕，感谢您的收听。[p3000]";
		if(type == 0) {
			text = "\n[p2000]本章节播讲完毕，感谢您的收听。[p3000]";
		}else if(type == 1) {
			text = "\n[p2000]播讲完毕，感谢您的收听。[p3000]";
		}else if(type == 2) {
			text = " ";
		}
		return text;
	}
	
	public static String chapterContentPreHandle(String text) {
		for (int i = 0; i < 2; i++) {
			if(text.indexOf("<br>")>=0) {
				text = text.substring(text.indexOf("<br>")+4, text.length());//
			}
		}
		logger.debug(text);
		if(text.indexOf("&lt;")>0) {
			text = text.substring(0, text.indexOf("&lt;"));
		}
		logger.debug(text);
		text = text.replaceAll("&nbsp;", "");//
		text = text.replaceAll("<br>", "");//
		text = text.replaceAll("#8226;", ".");//
		text = text.replaceAll(" ", "");//
		text = text.replaceAll("yinluàn", "淫乱");//
		text = text.replaceAll("mihun", "迷魂");//
		text = text.replaceAll("mo样", "模样");
		text = text.replaceAll("yin", "阴");//
		text = text.replaceAll("sè", "色");//
		text = text.replaceAll("xing", "性");//
		text = text.replaceAll("luàn", "乱");//
		text = text.replaceAll("mo", "摸");//
		text = text.replaceAll("dàng", "荡");//
		text = text.replaceAll("hn", "经理");//
		text = text.replaceAll("ku", "裤");//
		text = text.replaceAll("huo", "惑");//
		text = text.replaceAll("｜", "1");//
		text = text.replaceAll("bo", "波");//
		text = text.replaceAll("chuáng", "床");//
		text = text.replaceAll("lu", "露");//
		text = text.replaceAll("未完待续", "");//
		text = text.replaceAll("jing", "精");//
		text = text.replaceAll("jiāo", "交");//
		text = text.replaceAll("nong", "弄");//
		text = text.replaceAll("làng", "浪");//
		text = text.replaceAll("ji", "激");//
		text = text.replaceAll("méng", "蒙");//
		text = text.replaceAll("mén", "门");//
		text = text.replaceAll("shè", "射");//
		text = text.replaceAll("shi", "饰");//
		text = text.replaceAll("huā", "花");//
		text = text.replaceAll("chun", "春");//
		text = text.replaceAll("dong", "东");//
		text = text.replaceAll("wèizhi", "位置");//
		text = text.replaceAll("nǎi", "奶");//
		text = text.replaceAll("jiān", "奸");//
		text = text.replaceAll("hun", "魂");
		text = text.replaceAll("mi", "迷");
		text = text.replaceAll("md", "妈的");
		text = text.replaceAll("nv", "女");//
		text = text.replaceAll("si", "私");//
		text = text.replaceAll("[／]", "");//
		text = text.replaceAll("fu", "妇");//
		text = text.replaceAll("youhuo", "诱惑");//
		text = text.replaceAll("máo", "毛");//
		text = text.replaceAll("chā", "插");//
		text = text.replaceAll("xue", "血");//
		text = text.replaceAll("nèn", "嫩");//
		text = text.replaceAll("ting", "挺");//
		text = text.replaceAll("tui", "腿");//
		text = text.replaceAll("xiong", "胸");//
//		text = text.replaceAll("▲", "么");//
		text = text.replaceAll("tun", "臀");//
		text = text.replaceAll("you", "诱");//
		text = text.replaceAll("yu", "欲");//
		text = text.replaceAll("mm", "毫米");//
		text = text.replaceAll("cm", "厘米");
		text = text.replaceAll("kg", "千克");
		text = text.replaceAll("sāo", "骚");//
		text = text.replaceAll("liáo", "撩");//
		text = text.replaceAll("ntr", "强占");//
		text = text.replaceAll("pla", "解放军");//
		text = text.replaceAll("nato", "北约");//
		text = text.replaceAll("访问下载txt小说", "");//
		text = text.replaceAll("文學馆xguan.", "");//
		text = text.replaceAll("shén", "神");//
		text = text.replaceAll("iii级", "三级");//
		text = text.replaceAll("ii级", "二级");//
		text = text.replaceAll("i级", "一级");//
		text = text.replaceAll("激liè", "激烈");//
		text = text.replaceAll("平ri", "平日");//
		text = text.replaceAll("ri期", "日期");//
		text = text.replaceAll("ri报", "日报");//
		text = text.replaceAll("ri子", "日子");//
		///
		text = text.replaceAll("轩然[***]", "轩然大波");//
		text = text.replaceAll("奸夫[***]", "奸夫淫妇");//
		text = text.replaceAll("[***]珠江口", "封锁珠江口");//
		text = text.replaceAll("[***]琼州海峡", "封锁琼州海峡");//
		text = text.replaceAll("十有[***]", "十有八九");//
		text = text.replaceAll("十之[***]", "十有八九");//
		text = text.replaceAll("[***]名", "八九名");//
		text = text.replaceAll("[***]成", "八九成");//
		text = text.replaceAll("[***]线", "封锁线");//
		text = text.replaceAll("[***]概", "人大概");//
		text = text.replaceAll("[***]多", "人大多");//
		text = text.replaceAll("[***]带", "亚热带");//
		text = text.replaceAll("打破[***]", "打破封锁");//
		text = text.replaceAll("[***]徒", "基督徒");//
		text = text.replaceAll("[***]练", "操练");//
		text = text.replaceAll("[***]人", "日本人");//
		text = text.replaceAll("[***]家", "政治家");//
		text = text.replaceAll("[***]体制", "政治体制");//
		text = text.replaceAll("[***]保卫", "政治保卫");//
		text = text.replaceAll("[***]前途", "政治前途");//
		text = text.replaceAll("[***]操", "团体操");//
		text = text.replaceAll("[***]江面", "封锁江面");//
		text = text.replaceAll("海上[***]", "海上封锁");//
		text = text.replaceAll("[***]现", "中出现");//
		text = text.replaceAll("大[***]一场", "大干一场");//
		text = text.replaceAll("有[***]量", "有人大量");//
		text = text.replaceAll("[***]住", "封锁住");//
		text = text.replaceAll("江面[***]", "江面封锁");//
		text = text.replaceAll("[***]动", "暴动");//
		text = text.replaceAll("[***]正确", "政治正确");//
		text = text.replaceAll("[***]突破口", "封锁突破口");//
		text = text.replaceAll("[***]个人", "八九个人");//
		text = text.replaceAll("[***]倾向", "政治倾向");//
		text = text.replaceAll("[***]之过急", "操之过急");//
		text = text.replaceAll("[***]作性", "操作性");//
		text = text.replaceAll("[***]军", "操军");//
		text = text.replaceAll("[***]皇权", "封建皇权");//
		text = text.replaceAll("车[***]战", "车轮战");//
		text = text.replaceAll("[***]场", "操场");//
		text = text.replaceAll("[***]心", "操心");//
		text = text.replaceAll("[***]制度", "民主制度");//
		text = text.replaceAll("[***]子", "下身子");//
		text = text.replaceAll("[***]体", "身体");//
		text = text.replaceAll("[***]思想", "民主思想");//
		text = text.replaceAll("[***]家", "政治家");//
		text = text.replaceAll("[***]协商", "政治协商");//
		text = text.replaceAll("[***]概", "人大概");//
		text = text.replaceAll("[***]审查", "政治审查");//
		text = text.replaceAll("[***]污点", "政治污点");//
		text = text.replaceAll("[***]鬼子", "日本鬼子");//
		text = text.replaceAll("kmt", "国民党");//
		text = text.replaceAll("tg", "土共");//
		text = text.replaceAll("[***]了琼州海峡", "封锁了琼州海峡");//
		text = text.replaceAll("[***]广州湾", "封锁广州湾");//
		text = text.replaceAll("澳洲[***]约", "澳洲人大约");//
		text = text.replaceAll("男男[***]", "男男女女");//
		text = text.replaceAll("家[***]惊", "家人大惊");//
		text = text.replaceAll("有[***]喊", "有人大喊");//
		text = text.replaceAll("[***]演", "操演");//
		text = text.replaceAll("[***]教会", "基督教会");//
		text = text.replaceAll("亻卜", "仆");//
		text = text.replaceAll("[***]", "[---哔哔哔---]");//
//		text = text.replaceAll("(?m)^\\s*$"+System.lineSeparator(), "");//
		text = " " + text;
		return text.trim();
	}

	
	/** 
     * 判断字符串是否是乱码 
     * �
     * @param strName 字符串 
     * @return 是否是乱码 
     */  
    public static boolean isMessyCode(String strName) {  
        Pattern p = Pattern.compile("\\s*|t*|r*|n*");  
        Matcher m = p.matcher(strName);  
        String after = m.replaceAll("");  
        String temp = after.replaceAll("\\p{P}", "");  
        char[] ch = temp.trim().toCharArray();  
        float chLength = ch.length;  
        float count = 0;  
        for (int i = 0; i < ch.length; i++) {  
            char c = ch[i];  
            if (!Character.isLetterOrDigit(c)) {  
                if (!isChinese(c)) {  
                    count = count + 1;  
                }  
            }  
        }  
        float result = count / chLength;  
        if (result > 0.4) {  
            return true;  
        } else {  
            return false;  
        }  
   
    }
    
    /** 
     * 判断字符是否是中文 
     * 
     * @param c 字符 
     * @return 是否是中文 
     */  
    public static boolean isChinese(char c) {  
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);  
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A  
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION  
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION  
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {  
            return true;  
        }  
        return false;  
    }  
    
    /**
     * 是否含有***敏感词汇
     * @param str
     * @return
     */
    public static boolean isContainsStar(String str) {
    	return str.contains("***");
    }
    
    
    /**
     * 中文數字转阿拉伯数组【十万九千零六十  --> 109060】
     * @author 雪见烟寒
     * @param chineseNumber
     * @return
     */
    public static int chineseNumber2Int(String chineseNumber){
        int result = 0;
        int temp = 1;//存放一个单位的数字如：十万
        int count = 0;//判断是否有chArr
        char[] cnArr = new char[]{'一','二','三','四','五','六','七','八','九'};
        char[] chArr = new char[]{'十','百','千','万','亿'};
        for (int i = 0; i < chineseNumber.length(); i++) {
            boolean b = true;//判断是否是chArr
            char c = chineseNumber.charAt(i);
            for (int j = 0; j < cnArr.length; j++) {//非单位，即数字
                if (c == cnArr[j]) {
                    if(0 != count){//添加下一个单位之前，先把上一个单位值添加到结果中
                        result += temp;
                        temp = 1;
                        count = 0;
                    }
                    // 下标+1，就是对应的值
                    temp = j + 1;
                    b = false;
                    break;
                }
            }
            if(b){//单位{'十','百','千','万','亿'}
                for (int j = 0; j < chArr.length; j++) {
                    if (c == chArr[j]) {
                        switch (j) {
                        case 0:
                            temp *= 10;
                            break;
                        case 1:
                            temp *= 100;
                            break;
                        case 2:
                            temp *= 1000;
                            break;
                        case 3:
                            temp *= 10000;
                            break;
                        case 4:
                            temp *= 100000000;
                            break;
                        default:
                            break;
                        }
                        count++;
                    }
                }
            }
            if (i == chineseNumber.length() - 1) {//遍历到最后一个字符
                result += temp;
            }
        }
        return result;
    }
    
    /**
     * 自动补全div标签
     * @param text
     * @param voice
     * @param speed
     * @return
     */
    public static String divAutoComplete(String text, String voice, String speed) {
    	List<String> list = new ArrayList<String>(0);
    	int a = 0;
    	int b = 0;
    	while(a < text.length() - 1) {
    		b = text.indexOf("<div", a);
    		logger.debug("a:" + a + ",  b:" + b);
        	if(b > -1) {
        		list.add("<div voice=\"xiaohou\">" + text.substring(a, b) + "</div>");
        		a = b;
        		b = text.indexOf("</div>", a) + 6;
        		logger.debug("a:" + a + ",  b:" + b);
        		list.add(text.substring(a, b));
        		a = b;
        	}else {
        		logger.info("无div标签");
        		list.add("<div voice=\"xiaohou\">" + text.substring(a) + "</div>");
        		a = text.length();
        	}
    	}
    	StringBuffer sb = new StringBuffer();
    	for(String s:list) {
    		sb.append(s);
    	}
    	return sb.toString();
    }
}
